package home

import (
	"fmt"
	"go-cmdb/controllers"

	"go-cmdb/models"
	"strings"
	"time"
)

type ApiRes struct {
	Data interface{} `json:"data"`
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
}

//BaseController 重写基类
type BaseController struct {
	controllers.BaseController
}

func (b *BaseController) IgnoreLayout(fn func(act string) bool) {
	_, act := b.Controller.GetControllerAndAction()
	if fn(act) {
		b.Layout = ""
	}
}

//Prepare action前置处理
func (b *BaseController) Prepare() {

	b.TplExt = "html"

	if !b.IsAjax() {
		b.TplPrefix = "home/"
		b.Layout = "home/layout.html"
		//设置模板
		//b.Layout = "home/layout.html"
		b.Data["ts"] = time.Now().UnixNano()
		//TODO:权限判断
		settings := models.NewSetting()
		b.Data["sets"] = settings.GetMap()

	}
}

func (b *BaseController) OK(data interface{}) {
	b.Data["json"] = ApiRes{
		Code: 200,
		Data: data,
	}
	b.ServeJSON()
	return
}
func (b *BaseController) ERROR(msg string) {
	b.Data["json"] = ApiRes{
		Code: 500,
		Msg:  msg,
	}
	b.ServeJSON()
	return
}

func (b *BaseController) RES(code int, data interface{}, msg string) {
	b.Data["json"] = ApiRes{
		Code: code,
		Data: data,
		Msg:  msg,
	}
	b.ServeJSON()
	return
}
func (b *BaseController) View() {

	b.view("", nil)

	return
}
func (b *BaseController) ViewTpl(tpl string) {

	b.view(tpl, nil)

	return
}
func (b *BaseController) ViewTplData(tpl string, data map[string]interface{}) {

	b.view(tpl, data)

	return
}
func (b *BaseController) ViewData(data map[string]interface{}) {

	b.view("", data)

	return
}
func (b *BaseController) view(tpName string, data map[string]interface{}) {
	ctrl, act := b.Controller.GetControllerAndAction()
	ctrl = strings.ToLower(ctrl[0:strings.Index(ctrl, "Controller")])
	if len(tpName) <= 0 {
		b.TplName = fmt.Sprintf("%s/%s.html", strings.ToLower(ctrl), strings.ToLower(act))
	} else {
		b.TplName = fmt.Sprintf("%s/%s.html", strings.ToLower(ctrl), tpName)
	}

	if data != nil {
		for k, v := range data {
			b.Data[k] = v
		}
	}

	return
}
